<!-- 注册组件 -->
<template>
  <view class="register-container">
    <text class="register-title">注册账号</text>
    <uni-forms ref="form" :modelValue="userData">
      <uni-forms-item label="账号" required name="id">
        <uni-easyinput type="number" v-model="userData.id" placeholder="请输入账号" />
      </uni-forms-item>
      <uni-forms-item label="用户名" required name="username">
        <uni-easyinput type="text" v-model="userData.username" placeholder="请输入用户名" />
      </uni-forms-item>
      <uni-forms-item label="密码" required name="password">
        <uni-easyinput type="password" v-model="userData.password" placeholder="请输入密码" />
      </uni-forms-item>
      <uni-forms-item label="确认密码" required name="subpassword">
        <uni-easyinput type="password" v-model="userData.subpassword" placeholder="请再次输入密码" />
      </uni-forms-item>
    </uni-forms>
    <button class="btn-register" @click="submitForm">注册</button>
    <text class="tips-text">已有账号，去<text class="tips-login" @click="gotoLogin">登录</text></text>
  </view>
</template>

<script>
  import { mapState } from 'vuex'
  export default {
    name: "my-register",
    options: {
      styleIsolation: 'shared' // 解除样式隔离，目的是修改uni-ui的组件样式
    },
    data() {
      return {
        userData: {
          id: '', //账号
          username: '', //用户名
          password: '', //密码
          subpassword: '' //确认密码
        },
        // 表单校验规则
        rules: {
          // 对id字段进行必填验证
          id: {
            // 当前表单域的字段中文名，可不填写
            label: '账号',
            // id 字段的校验规则
            rules: [
              // 校验 id 不能为空
              {
                required: true,
                errorMessage: '请填写账号！',
              },
              // 对id字段进行长度验证
              {
                minLength: 6,
                maxLength: 6,
                errorMessage: '{label}长度为 {minLength} 个字符！',
              },
              // 账号重复时，自定义表单验证
              {
                validateFunction: async function(rule, value, data, callback) {
                  // 获取已注册用户的id，username
                  const { data: res } = await uni.$http.get('/api/public/v1/users/checkregister')
                  if (res.meta.status !== 200) return console.log('获取已注册用户数据失败！')
                  const result = res.message.find(item => item.id == value)
                  if (result) callback('该账号已存在！')
                  return true
                }
              }
            ]
          },
          username: {
            label: '用户名',
            rules: [{
                required: true,
                errorMessage: '请填写{label}！'
              },
              // 用户名重复时，自定义表单验证
              {
                validateFunction: async function(rule, value, data, callback) {
                  // 获取已注册用户的id，username
                  const { data: res } = await uni.$http.get('/api/public/v1/users/checkregister')
                  if (res.meta.status !== 200) return console.log('获取已注册用户数据失败！')
                  const result = res.message.find(item => item.username == value)
                  if (result) callback('该用户名已存在！')
                  return true
                }
              }
            ],
          },
          password: {
            label: '密码',
            rules: [{
                required: true,
                errorMessage: '请填写密码！'
              },
              // 对password字段进行长度验证
              {
                minLength: 4,
                maxLength: 8,
                errorMessage: '{label}长度为 {minLength} 到 {maxLength} 个字符！',
              }
            ],
          },
          subpassword: {
            label: '确认密码',
            rules: [{
                required: true,
                errorMessage: '请填写密码！'
              },
              // 对subpassword字段进行长度验证
              {
                minLength: 4,
                maxLength: 8,
                errorMessage: '密码长度为 {minLength} 到 {maxLength} 个字符！',
              },
              // 自定义表单验证，验证确认密码和密码是否相同
              {
                validateFunction: function(rule, value, data, callback) {
                  if (data.subpassword != data.password) callback('两个密码不同！')
                  return true
                }
              }
            ],
          },
        },
        // 注册成功后，三秒后跳转登录页
        seconds: 3,
        // 延时器id
        timer: null
      }
    },
    computed: {
      // 已注册用户的id和username，用于注册前自定义表单验证，查找用户名和账号是否重复
      // ...mapState('m_user', ['registeredUser'])
    },
    onReady() {
      // 需要在onReady中设置表单校验规则，注意：此处设置后，表单中不用设置:rules
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      submitForm(form) {
        this.$refs.form.validate().then(async res => {
          // console.log('表单数据信息：', res);
          // 所有表单验证通过，注册用户
          const { data: result } = await uni.$http.post('/api/public/v1/users/register', this.userData)
          if (result.meta.status !== 200) return uni.$showMsg('注册失败！')
          // 注册成功，3s后跳转到登录页
          this.delayGotoLogin()
        }).catch(err => {
          // console.log('表单错误信息：', err);
        })
      },
      // 跳转到登录页
      gotoLogin() {
        this.$emit("showLogin", false)
      },
      // 展示倒计时的提示消息
      showTips(n) {
        uni.showToast({
          icon: 'success',
          title: '注册成功！' + n,
          mask: true,
          duration: 1500
        })
      },
      // 延时跳转到登录页面
      delayGotoLogin() {
        // 延时回到登录页面
        this.showTips(this.seconds)
        this.timer = setInterval(() => {
          this.seconds--
          if (this.seconds <= 0) {
            clearInterval(this.timer)
            this.gotoLogin()
            // 重置延迟时间为3，否则，不登录时，第二次点击结算按钮，将不再延时跳转
            return this.seconds = 3 //下边的showTips不再执行
          }
          this.showTips(this.seconds)
        }, 1000)
      }


    }
  }
</script>

<style lang="scss" scoped>
  .register-container {
    height: 1000rpx;
    background-color: #F8F8F8;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    overflow: hidden;

    .register-title {
      font-size: 30px;
      font-weight: bold;
      color: #C00000;
    }

    &::after {
      content: '';
      width: 100%;
      height: 40px;
      background-color: white;
      position: absolute;
      bottom: 0;
      border-radius: 100%;
      transform: translateY(50%);
    }



    ::v-deep .uni-forms {
      width: 80%;
      margin: 20px 0;

      .uni-forms-item__label:nth-child(1) {
        white-space: nowrap;
      }
    }


    .btn-register {
      color: white;
      background-color: #C00000;
      width: 90%;
      border-radius: 100px;
      margin-bottom: 15px;
    }

    .tips-text {
      font-size: 12px;
      color: gray;

      .tips-login {
        color: #C00000;
        text-decoration: underline;
      }
    }
  }
</style>
